package org.company.earth.apache;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

public class HttpClientUtil {
    
    private static Logger logger = Logger.getLogger(HttpClientUtil.class);
    
    public static String get(String uri) throws ClientProtocolException, IOException {
        HttpGet post = new HttpGet(uri);
        return request(post);
    }
    
    public static String post(String uri) throws ClientProtocolException, IOException {
        HttpPost post = new HttpPost(uri);
        return request(post);
    }
    
    public static String request(HttpUriRequest request) throws ClientProtocolException, IOException{
        return request(request,"UTF-8");
    }
    
    public static String request(HttpUriRequest request,String charset) throws ClientProtocolException, IOException {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = client.execute(request);
        if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.error(response.getStatusLine());
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if(entity != null) {
            EntityUtils.toString(entity, Charset.forName(charset));
        }
        logger.debug(request.getURI() + ":" + result);
        return result;
    }
    
    /**
     * 带参数的chunk post请求
     * @param uri
     * @param xml
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String chunkPost(String uri,String xml) throws ClientProtocolException, IOException {
        HttpPost post = new HttpPost(uri);
        StringEntity entity = new StringEntity(xml);
        entity.setChunked(true);
        post.setEntity(entity);
        return request(post);
    }
}
